namespace ETestIT.Web.Controllers.Extensions
{
    using System.IO;
    using System.Web;
    using System.Web.Mvc;
    using Core;

    public static class RequestExtensions
    {
        public static void GetResumeFromRequest(this Controller theController, Resume theResume)
        {
            if (theController.Request == null)
                return;

            foreach (string file in theController.Request.Files)
            {
                var httpPostedFile = theController.Request.Files[file];
                if (httpPostedFile.ContentLength == 0)
                    continue;

                var nFileLen = httpPostedFile.ContentLength;

                if (nFileLen > 0)
                {
                    var httpPostedFileByteArray = new byte[nFileLen];
                    httpPostedFile.InputStream.Read(httpPostedFileByteArray, 0, nFileLen);

                    var strFilename = Path.GetFileName(httpPostedFile.FileName);

                    theResume.Content = httpPostedFileByteArray;
                    theResume.Name = strFilename;
                    theResume.ContentType = httpPostedFile.ContentType;
                }
            }
        }

        public static void WriteResumeToResponse(this ControllerContext httpResponse, Resume resume)
        {
            var httpResponseBase = httpResponse.HttpContext.Response;

            httpResponseBase.ContentType = resume.ContentType;
            httpResponseBase.AddHeader(
                "Content-Disposition",
                "attachment;filename=" + HttpUtility.UrlEncode(resume.Name, System.Text.Encoding.UTF8));
            httpResponseBase.BinaryWrite(resume.Content);
            httpResponseBase.End();
        }
    }
}